/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package http

import (
	"mime/multipart"
	"net"
	"net/http"
	"strings"

	"github.com/emicklei/go-restful"
)

const defaultMultipartMemory = 32 << 20 // 32 MB

func ReadFile(req *restful.Request, name string) (*multipart.FileHeader, error) {
	if req.Request.MultipartForm == nil {
		if err := req.Request.ParseMultipartForm(defaultMultipartMemory); err != nil {
			return nil, err
		}
	}
	f, fh, err := req.Request.FormFile(name)
	if err != nil {
		return nil, err
	}
	f.Close()
	return fh, err
}

func ReadFiles(req *restful.Request, name string) ([]*multipart.FileHeader, error) {
	if req.Request.MultipartForm == nil {
		if err := req.Request.ParseMultipartForm(defaultMultipartMemory); err != nil {
			return nil, err
		}
	}
	form := req.Request.MultipartForm
	files := form.File[name]
	return files, nil
}

// 获取http请求来源IP地址
func GetRequestIp(req *http.Request) string {
	header := req.Header

	ip := header.Get("X-Forwarded-For")
	ipList := strings.Split(ip, ",")
	for _, tmpIp := range ipList {
		netIP := net.ParseIP(tmpIp)
		if netIP != nil {
			return tmpIp
		}
	}

	ip = header.Get("X-Real-IP")
	if ip == "" {
		ip, _, _ = net.SplitHostPort(req.RemoteAddr)
	}
	netIP := net.ParseIP(ip)
	if netIP == nil {
		return ip
	}
	if ipv4 := netIP.To4(); ipv4 != nil {
		return ipv4.String()
	}
	return ip
}
